package com.hertz.alarm.service.impl;

import java.io.IOException;
import java.util.Collection;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.hertz.alarm.entity.MatchNba;
import com.hertz.alarm.service.EntityService;
import com.hertz.alarm.service.FetchNbaData;
import com.hertz.alarm.service.MatchNbaService;
import com.hertz.alarm.util.ApiConstants4sinaNBA;
import com.hertz.alarm.util.Constants4HTTP;
import com.hertz.alarm.util.ConstantsType;
import com.hertz.alarm.util.DateUtils;
import com.hertz.alarm.util.PatternUtil;
@Service
public class FetchNbaDataImpl extends BaseServiceImpl implements FetchNbaData {
	private Logger logger = LoggerFactory.getLogger(FetchNbaDataImpl.class);
	private final String haiyou = "还有";
	private final String jieshu = "结束";
	private String regex_remain = "(?<=还有).*";
	private String regex_period = ".*(?=还有)";
	@Resource
	private MatchNbaService matchNbaService;
	@Resource
	private EntityService entityService;
	@Override
	public void fetchCurrentMatchData() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void fetchCurrentMatchData(String sourceId) {
		try {
			Connection connection = Jsoup.connect(String.format(ApiConstants4sinaNBA.MATCH_DATA,"xml",sourceId));
			connection.timeout(Constants4HTTP.TIMEOUT);
			connection.userAgent(Constants4HTTP.HEADER_USERAGENT);
			connection.referrer(Constants4HTTP.SINA_REFERRER);
			connection.parser(Parser.xmlParser());
			Document doc = connection.get();
			Elements periodElements = doc.select("root > result > data > remain > period");
			Elements statusElements = doc.select("root > result > data > remain > status");
			Elements hostScoresElements = doc.select("root > result > data > host > scores");
			Elements guestScoresElements = doc.select("root > result > data > guest > scores");
			MatchNba matchNba = matchNbaService.getBySourceId(sourceId);
			if(matchNba == null){
				logger.error("no match sourceId:{}",sourceId);
			}else{
				String status = statusElements.get(0).text();
				String period = periodElements.get(0).text();
				if(StringUtils.isNotBlank(period) && Byte.valueOf(period) != 0){
//				if(status.indexOf(jieshu) >= 0){
//					if(status.indexOf(jieshu) >= 0 || matchNba.getPeriod() == 0){
						logger.info("pre update : {}",matchNba.toString());
						matchNba.setPeriod(Byte.valueOf(period));
						matchNba.setStatus(status);
						Integer hostScore = 0;
						Integer guestScore = 0;
						for (int i = 0; i < hostScoresElements.size(); i++) {
							hostScore = hostScore + Short.valueOf(hostScoresElements.get(i).text());
							guestScore = guestScore + Short.valueOf(guestScoresElements.get(i).text());
						}
						matchNba.setHostScore(hostScore.shortValue());
						matchNba.setGuestScore(guestScore.shortValue());
						Collection<String> remains = PatternUtil.matcher(status, regex_remain);
						if(remains != null && remains.size() > 0){
							matchNba.setRemain(remains.toArray(new String[]{})[0]);
						}else{
							matchNba.setRemain("0");
						}
						
						matchNba.setUtime(System.currentTimeMillis());
						logger.info("update to -> {}",matchNba.toString());
						matchNbaService.update(matchNba);
//					}
				}else{
					logger.debug("sourceId:{} status:{}",sourceId,status);
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage());
		}
	}

	@Override
	public void fetchMatchSchedule() {
		String date = DateUtils.timeFormat(System.currentTimeMillis(), DateUtils.Y_M_D);
		fetchMatchSchedule(date);
	}
	

	@Override
	public void fetchMatchSchedule(String ymd) {
		try {
			Connection connection = Jsoup.connect(String.format(ApiConstants4sinaNBA.MATCH_SCHEDUL,"xml",ymd));
			connection.timeout(Constants4HTTP.TIMEOUT);
			connection.userAgent(Constants4HTTP.HEADER_USERAGENT);
			connection.referrer(Constants4HTTP.SINA_REFERRER);
			connection.parser(Parser.xmlParser());
			Document doc = connection.get();
			Elements timeElements = doc.select("root > result > data > time");
			Elements dateElements = doc.select("root > result > data > date");
			Elements hostTeamElements = doc.select("root > result > data > team2_id");
			Elements guestTeamElements = doc.select("root > result > data > team1_id");
			Elements idElements = doc.select("root > result > data > id");
			for (int i = 0; i < idElements.size(); i++) {
				String id = idElements.get(i).text();
				String matchDay = dateElements.get(i).text();
				String matchTime = timeElements.get(i).text();
				String hostId = hostTeamElements.get(i).text();
				String guestId = guestTeamElements.get(i).text();
				long now = System.currentTimeMillis();
				MatchNba matchNba = new MatchNba();
				matchNba.setCtime(now);
				matchNba.setGuestScore((short)0);
				matchNba.setGuestTeamId(Byte.valueOf(guestId));
				matchNba.setHostScore((short)0);
				matchNba.setHostTeamId(Byte.valueOf(hostId));
				matchNba.setMatchTime(matchTime);
				matchNba.setMatchDay(matchDay);
				matchNba.setPeriod((byte)0);
				matchNba.setRemain("0");
				matchNba.setSeason(nbaConfig.getNbaConfSeason());
				matchNba.setSourceId(id);
				matchNba.setStatus("未赛");
				matchNba.setType(ConstantsType.MATCH_TYPE.pre_game.getValue());
				matchNba.setUtime(now);
				entityService.save(matchNba);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage());
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
